package com.example.onlinefood.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DatabaseUpdater implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseUpdater.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        logger.info("开始检查并更新数据库表结构");
        
        try {
            // 检查rating字段是否存在
            boolean hasRatingColumn = hasColumn("restaurants", "rating");
            boolean hasDistanceColumn = hasColumn("restaurants", "distance");
            
            if (!hasRatingColumn || !hasDistanceColumn) {
                logger.info("需要更新restaurants表结构，添加缺失的字段");
                
                if (!hasRatingColumn) {
                    jdbcTemplate.execute("ALTER TABLE restaurants ADD COLUMN rating DECIMAL(3,2) DEFAULT 0");
                    logger.info("已添加rating字段");
                }
                
                if (!hasDistanceColumn) {
                    jdbcTemplate.execute("ALTER TABLE restaurants ADD COLUMN distance DECIMAL(5,2) DEFAULT 0");
                    logger.info("已添加distance字段");
                }
                
                logger.info("表结构更新完成");
            } else {
                logger.info("restaurants表结构已经包含所有必要的字段，无需更新");
            }
        } catch (Exception e) {
            logger.error("更新数据库表结构失败: {}", e.getMessage(), e);
        }
    }
    
    private boolean hasColumn(String tableName, String columnName) {
        try {
            String query = "SELECT COUNT(*) FROM information_schema.columns WHERE table_name = ? AND column_name = ?";
            Integer count = jdbcTemplate.queryForObject(query, Integer.class, tableName, columnName);
            return count != null && count > 0;
        } catch (Exception e) {
            logger.error("检查字段是否存在失败: {}", e.getMessage());
            return false;
        }
    }
}